<?php
/*
	Copyright (C) 2008 - 2012 Inanta Martsanto
	Inanta Martsanto (inanta@inationsoft.com)

	This file is part of Koma.

	Koma is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Koma is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Koma.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Inationsoft\Koma;

use Inationsoft\NS;
use Inationsoft\NS\Core\Config;

/**
 *Handle Koma current user object
 *
 *@author Inanta Martsanto <inanta@inationsoft.com>
 *@property-read int $UID User ID for current user
 *@property-read string $Username User name user for current user
 *@property-read string $Fullname Full name for current user
 *@property-read array $Role Role for current user
 *@property-read string $Token Unique token generated by system for current user
 */
class User extends NS\SingletonObject {
	private static $_user;

	function __construct($user_data = null) {
		if($user_data != null) $this->createProperties($user_data);
		else {
			$this->createProperties(array(
				'UID' => 0,
				'Role' => array('0' => 'Anonymous'),
				'Username' => null,
				'FullName' => 'Anonymous',
				'Token' => null)
			);
		}
	}

	function isAdmin() { return (isset($this->Role[KOMA_ROLE_ADMIN])); }
	function isUser() { return !(isset($this->Role[KOMA_ROLE_ANONYMOUS])); }
	function hasRole($role) { return in_array($role, $this->Role); }
	function hasRID($rid) { return isset($this->Role[$rid]); }
	function lock() { $this->setReadOnlyProperties(array('UID', 'Role', 'Username', 'FullName', 'Token')); }

	static function getInstance() {
		if(isset($_SESSION['Koma']['User'])) {
			$user = unserialize($_SESSION['Koma']['User']);

			if($user->Token == md5($_SESSION['Koma']['Token'] . Config::getInstance()->Application->Salt)) return $user;
		}

		return self::createInstance(__CLASS__);
	}
}
?>